package com.adaxi.adc.business.manager.utils;


import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class JwtUtil {
    //设置token过期时间
    @Value("${my.secretExpirationTime}")
    private long EXPIRATION_TIME;
    //你的密码，用于加密
    @Value("${my.privateSecret}")
    private String SECRET;

    /**
     * 生成token
     * @param username
     * @return
     */
    public  String generateToken(String username) {
        return Jwts.builder()
                .setSubject(username)
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();
    }

    /**
     * 解析token 返回用户名
     * @param token
     * @return
     */
    public  String getClaimsFromToken(String token) {
        return Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token)
                .getBody().getSubject();
    }

    /**
     * 验证Token
     * @param token
     * @return
     */
    public  boolean validateToken(String token) {
        try {
            Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token);
            return true;
        } catch(Exception e) {
            return false;
        }
    }

}
